package com.androturka;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import android.widget.Spinner;

public class FiltersActivity extends Activity {

	private ListView filtersListView;
	private Button   filtreEkleButton;
	private Resources res;
	boolean needUpdate = false;
	
	private final int     MAXMESAFE 				= 1000;
	private final double  MINDEPREMBUYUKLUGU 		= 0.0;
	private int           currentMaxMesafe 			= MAXMESAFE;
	private int           cityID 					= 0;
	private double        currentMinDepremBuyuklugu = MINDEPREMBUYUKLUGU;
	private int           finalPosition;
	
	private ConfigurationManager configurationManager;
	
	static final int DIALOG_DELETE_FILTER = 0;
	AlertDialog alert;
	ArrayList<Filter> filterArrayList;
	ArrayAdapter<Filter> arrayAdapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.filters_activity);
		
		res = getResources();
		configurationManager = new ConfigurationManager(getApplicationContext());
 		//Log.d("Settings", "Filtre arraylist size = " + configurationManager.getFilters().size());

 		filterArrayList = configurationManager.getFilters();
		//arrayAdapter = new ArrayAdapter<Filter>(this, android.R.layout.simple_list_item_1, filterArrayList);
		FilterAdapter arrayAdapter = new FilterAdapter(getApplicationContext(),filterArrayList.toArray(new Filter[filterArrayList.size()]));

		filtersListView = (ListView)findViewById(R.id.filtersListView);
		
		filtersListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
    		    finalPosition = position;
				AlertDialog.Builder builder = new AlertDialog.Builder(FiltersActivity.this);
				builder.setMessage(res.getString(R.string.filtreSilmeYazisi))
				       .setCancelable(false)
				       .setPositiveButton(res.getString(R.string.evetYazisi), new DialogInterface.OnClickListener() {
				    	   @Override
						public void onClick(DialogInterface dialog, int id) {
							//secilen filtreyi sil
							Object o = filtersListView.getItemAtPosition(finalPosition);
							Filter chosenFilter = (Filter)o;
							configurationManager.deleteFilter(chosenFilter.filterid);
							
							//Bu 3 satir mantiksiz, ancak deleteFilter dedigimizde arrayList update olmadigindan bunu yapmak zorunda kaldim.
							filterArrayList = configurationManager.getFilters();
							//arrayAdapter = new ArrayAdapter<Filter>(FiltersActivity.this, android.R.layout.simple_list_item_1, filterArrayList);
							FilterAdapter arrayAdapter = new FilterAdapter(getApplicationContext(),filterArrayList.toArray(new Filter[filterArrayList.size()]));

							//arrayAdapter.notifyDataSetChanged();
							filtersListView.invalidateViews();
							filtersListView.setAdapter(arrayAdapter);
							
							needUpdate = true;
						}
					   })
					   .setNegativeButton(res.getString(R.string.hayirYazisi), new DialogInterface.OnClickListener() {
						   @Override
						public void onClick(DialogInterface dialog, int which) {
							   dialog.cancel();
						   }
					   });
				alert = builder.create();
				showDialog(DIALOG_DELETE_FILTER);
			}
		});
		filtersListView.setAdapter(arrayAdapter);
		
		
	    Spinner citySpinner = (Spinner) findViewById(R.id.cityspinner);
	    ArrayAdapter<CharSequence> cityadapter = ArrayAdapter.createFromResource(
	            this, R.array.city_array, android.R.layout.simple_spinner_item);
	    cityadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    citySpinner.setAdapter(cityadapter);		

	    final Spinner magnitudeSpinner = (Spinner) findViewById(R.id.magnitudeSpinner);
	    ArrayAdapter<CharSequence> manginuteAdapter = ArrayAdapter.createFromResource(
	            this, R.array.magnitude_array, android.R.layout.simple_spinner_item);
	    manginuteAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    magnitudeSpinner.setAdapter(manginuteAdapter);		
	    magnitudeSpinner.setSelection(2);
	    
	    final Spinner distanceSpinner = (Spinner) findViewById(R.id.distanceSpinner);
	    ArrayAdapter<CharSequence> distanceAdapter = ArrayAdapter.createFromResource(
	            this, R.array.distance_array, android.R.layout.simple_spinner_item);
	    distanceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    distanceSpinner.setAdapter(distanceAdapter);		
		distanceSpinner.setSelection(0);
	    
	    citySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
	    
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				//Toast.makeText(parent.getContext(), pos + " - city is " +
				//parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
				cityID = pos;
				if ( cityID == 0 )
				{
					distanceSpinner.setEnabled(false);
				}
				else
					distanceSpinner.setEnabled(true);
					
			}

		    @Override
			public void onNothingSelected(AdapterView<?> parent) {
		    	// Do nothing.
		    }
	    });
	    
		

	    magnitudeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
	    
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				//Toast.makeText(parent.getContext(), pos + " - magnitude is " +
				//parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
				currentMinDepremBuyuklugu = Double.parseDouble((String) parent.getItemAtPosition(pos));
			}

		    @Override
			public void onNothingSelected(AdapterView<?> parent) {
		    	// Do nothing.
		    }
	    });		

	    distanceSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
	    
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				//Toast.makeText(parent.getContext(), pos + " - distance is " +
				//parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
				currentMaxMesafe = Integer.parseInt((String) parent.getItemAtPosition(pos));
			}

		    @Override
			public void onNothingSelected(AdapterView<?> parent) {
		    	// Do nothing.
		    }
	    });
	    

	    filtreEkleButton = (Button)findViewById(R.id.filtreEkleButton);
		filtreEkleButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				filterArrayList = configurationManager.getFilters();
				
				int i = 0;
				boolean insertable = true;
				for ( i = 0; i < filterArrayList.size(); i++ )
				{
					if ( filterArrayList.get(i).cityid == cityID ){
						Toast.makeText(getApplicationContext(), "Aynı Şehir için birden fazla filtre eklenemez", Toast.LENGTH_SHORT).show();
						insertable = false;
						break;
					} 					
				}	
				
				if ( insertable ) {
					configurationManager.insertFilter(currentMinDepremBuyuklugu, currentMaxMesafe, cityID);
					Toast.makeText(getApplicationContext(), "Yeni filtre eklendi", Toast.LENGTH_SHORT).show();
					
					//Bu 3 satir mantiksiz, ancak deleteFilter dedigimizde arrayList update olmadigindan bunu yapmak zorunda kaldim.
					filterArrayList.add(filterArrayList.size(), new Filter(0, (float) currentMinDepremBuyuklugu, currentMaxMesafe, cityID));
					filterArrayList = configurationManager.getFilters();
					//filarrayAdapter = new ArrayAdapter<Filter>(FiltersActivity.this, android.R.layout.simple_list_item_2, filterArrayList);
					FilterAdapter arrayAdapter = new FilterAdapter(getApplicationContext(),filterArrayList.toArray(new Filter[filterArrayList.size()]));
					
					//arrayAdapter.notifyDataSetChanged();
					filtersListView.invalidateViews();
					filtersListView.setAdapter(arrayAdapter);
					
					needUpdate = true;
					
				}
			}
		});
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		if (id == DIALOG_DELETE_FILTER)
		{
			return alert;
		}
		return dialog;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
		if ( needUpdate ){
			ConfigurationSender sender = new ConfigurationSender(getApplicationContext());
			try {
				sender.sendConfiguration();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		if (configurationManager != null)
			configurationManager.cleanup();
	}

}


